package com.twu.biblioteca;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

public class Library<T extends Item> {
    private HashMap<T, Boolean> items;

    public Library() {
        this(new ArrayList<T>());
    }

    public Library(ArrayList<T> items) {
        this.items = new HashMap<T, Boolean>();

        for (T item : items) {
            this.items.put(item, true);
        }
    }

    public T getItemByTitle(String title) {
        for (T item : items.keySet()) {
            if (item.getTitle().equals(title)) {
                return item;
            }
        }

        return null;
    }

    public Collection<T> getAvailableItems() {
        ArrayList<T> availableItems = new ArrayList<T>();

        for (Map.Entry<T, Boolean> element : items.entrySet()) {
            if (element.getValue()) {
                availableItems.add(element.getKey());
            }
        }

        return availableItems;
    }

    public boolean checkoutItem(T item) {
        if (!items.containsKey(item)) {
            return false;
        }

        if (!items.get(item)) {
            return false;
        }

        items.put(item, false);
        return true;
    }

    public boolean returnItem(T item) {
        if (!items.containsKey(item)) {
            return false;
        }

        if (items.get(item)) {
            return false;
        }

        items.put(item, true);
        return true;
    }
}
